<?php
/**
 * Created by PhpStorm.
 * User: 小灰灰
 * Date: 2021-04-21
 * Time: 下午6:20:41
 * Info:
 */

namespace app\common\service\admin;

use app\common\model\Admin;
use app\common\model\AuthGroup;
use app\common\model\AuthGroupAccess;
use libs\Tree2;
use think\facade\Db;
use think\facade\Request;
use think\facade\Session;

/**
 * 权限认证类
 * 功能特性：
 * 1，是对规则进行认证，不是对节点进行认证。用户可以把节点当作规则名称实现对节点进行认证。
 *      $auth=new Auth();  $auth->check('规则名称','用户id')
 * 2，可以同时对多条规则进行认证，并设置多条规则的关系（or或者and）
 *      $auth=new Auth();  $auth->check('规则1,规则2','用户id','and')
 *      第三个参数为and时表示，用户需要同时具有规则1和规则2的权限。 当第三个参数为or时，表示用户值需要具备其中一个条件即可。默认为or
 * 3，一个用户可以属于多个用户组(think_auth_group_access表 定义了用户所属用户组)。我们需要设置每个用户组拥有哪些规则(think_auth_group 定义了用户组权限)
 * 4，支持规则表达式。
 *      在think_auth_rule 表中定义一条规则，condition字段就可以定义规则表达式。 如定义{score}>5  and {score}<100
 * 表示用户的分数在5-100之间时这条规则才会通过。
 * 5，支持放行public_方法（2021-05-26，小灰灰修改）
 *      如果访问的方法里包含：public_，不做权限验证，直接放行，为true
 */
class AuthService
{

    /**
     * @var object 对象实例
     */
    protected static $instance;

    protected $rules = [];

    protected $auth;

    public $group_id;

    public $uid;

    public $breadcrumb = [];

    /**
     * 当前请求实例
     * @var Request
     */
    protected $request;

    //默认配置
    protected $config = [
        'auth_on'           => 1, // 权限开关
        'auth_type'         => 1, // 认证方式，1为实时认证；2为登录认证。
        'auth_group'        => 'auth_group', // 用户组数据表名
        'auth_group_access' => 'auth_group_access', // 用户-用户组关系表
        'auth_rule'         => 'auth_rule', // 权限规则表
        'auth_user'         => 'admin', // 用户信息表
    ];

    public function __construct()
    {
        if ($auth = config('auth.auth')) {
            $this->config = array_merge($this->config, $auth);
        }
        // 初始化request
        $this->request = Request::instance();
    }

    /**
     * 初始化
     * @access public
     *
     * @param array $options 参数
     *
     * @return Auth
     */
    public static function instance($options = [])
    {

        if (is_null(self::$instance)) {
            self::$instance = new static($options);
        }

        return self::$instance;
    }

    /**
     * 检查权限
     *
     * @param string|array $name     需要验证的规则列表,支持逗号分隔的权限规则或索引数组
     * @param int          $uid      认证用户的id
     * @param string       $relation 如果为 'or' 表示满足任一条规则即通过验证;如果为 'and'则表示需满足所有规则才能通过验证
     * @param string       $mode     执行验证的模式,可分为url,normal
     *
     * @return bool 通过验证返回true;失败返回false
     */
    public function check($name, $uid, $relation = 'or', $mode = 'url')
    {
        if ( ! $this->config['auth_on']) {
            return true;
        }

        // 获取用户需要验证的所有有效规则列表
        $rulelist = $this->getRuleList($uid);
        if (in_array('*', $rulelist)) {
            return true;
        }
        if (is_string($name)) {
            $name = strtolower($name);
            if (strpos($name, ',') !== false) {
                $name = explode(',', $name);
            } else {
                $name = [$name];
            }
        }
        $list = []; //保存验证通过的规则名
        if ('url' == $mode) {
            $REQUEST = unserialize(strtolower(serialize($this->request->param())));
        }

        foreach ($rulelist as $rule) {
            $query = preg_replace('/^.+\?/U', '', $rule);
            if ('url' == $mode && $query != $rule) {
                parse_str($query, $param); //解析规则中的param
                $intersect = array_intersect_assoc($REQUEST, $param);
                $rule      = preg_replace('/\?.*$/U', '', $rule);
                if (in_array($rule, $name) && $intersect == $param) {
                    //如果节点相符且url参数满足
                    $list[] = $rule;
                }
            } else {
                if (in_array($rule, $name)) {
                    $list[] = $rule;
                }
            }
        }

        //如果访问的方法里包含：public_，不做权限验证，为true
        foreach ($name as $v) {
            if (strstr(substr(strrchr($v, '/'), 1), 'public_')) {
                return true;
            }
        }
        if ('or' == $relation && ! empty($list)) {
            return true;
        }
        $diff = array_diff($name, $list);
        if ('and' == $relation && empty($diff)) {
            return true;
        }

        return false;
    }

    /**
     * 根据用户id获取用户组,返回值为数组
     *
     * @param int $uid 用户id
     *
     * @return array       用户所属的用户组 array(
     *                  array('uid'=>'用户id','group_id'=>'用户组id','name'=>'用户组名称','rules'=>'用户组拥有的规则id,多个,号隔开'),
     *                  ...)
     */
    public static function getGroups($uid)
    {
        static $groups = [];
        if (isset($groups[$uid])) {
            return $groups[$uid];
        }
        // 执行查询
        $user_groups  = Db::name('auth_group_access')->alias('aga')->join('auth_group'.' ag', 'aga.group_id = ag.id',
            'LEFT')->field('aga.uid,aga.group_id,ag.id,ag.pid,ag.name,ag.rules')->where("aga.uid='{$uid}' and ag.status=1")->select();
        $groups[$uid] = $user_groups ?: [];

        return $groups[$uid];
    }

    /**
     * 获得权限规则列表
     *
     * @param int $uid 用户id
     *
     * @return array
     */
    public function getRuleList($uid)
    {
        static $_rulelist = []; //保存用户验证通过的权限列表
        if (isset($_rulelist[$uid])) {
            return $_rulelist[$uid];
        }
        if (2 == $this->config['auth_type'] && Session::has('_rule_list_'.$uid)) {
            return Session::get('_rule_list_'.$uid);
        }

        // 读取用户规则节点
        $ids = self::getRuleIds($uid);
        if (empty($ids)) {
            $_rulelist[$uid] = [];

            return [];
        }

        // 筛选条件
        /*$where = [
            'status' => 1
        ];
        if (!in_array('*', $ids)) {
            $ids = ['in', $ids];
        }*/
        if ( ! in_array('*', $ids)) {
            $where = ['id' => $ids];
        } else {
            $where = [];
        }
        //读取用户组所有权限规则
        if (cache('cache_auth_rules')) {
            $this->rules = cache('cache_auth_rules');
        } else {
            $this->rules = Db::name($this->config['auth_rule'])->where($where)->select();

            cache('cache_auth_rules', $this->rules);
        }
        //$this->rules = Db::name($this->config['auth_rule'])->where($where)->select();

        //循环规则，判断结果。
        $rulelist = []; //
        if (in_array('*', $ids)) {
            $rulelist[] = "*";
        }
        $condition = '';
        foreach ($this->rules as $rule) {
            //超级管理员无需验证condition
            if ( ! empty($rule['condition']) && ! in_array('*', $ids)) {
                //根据condition进行验证
                $user    = $this->getUserInfo($uid); //获取用户信息,一维数组
                $command = preg_replace('/\{(\w*?)\}/', '$user[\'\\1\']', $rule['condition']);
                @(eval('$condition=('.$command.');'));
                if ($condition) {
                    $rulelist[$rule['id']] = strtolower($rule['node']);
                }
            } else {
                //只要存在就记录
                $rulelist[$rule['id']] = strtolower($rule['node']);
            }
        }
        $_rulelist[$uid] = $rulelist;
        //登录验证则需要保存规则列表
        if (2 == $this->config['auth_type']) {
            //规则列表结果保存到session
            Session::set('_rule_list_'.$uid, $rulelist);
        }

        return array_unique($rulelist);
    }

    public static function getRuleIds($uid)
    {
        //读取用户所属用户组
        $groups = self::getGroups($uid);
        $ids    = []; //保存用户所属用户组设置的所有权限规则id
        foreach ($groups as $g) {
            $ids = array_merge($ids, explode(',', trim($g['rules'], ',')));
        }
        $ids = array_unique($ids);

        return $ids;
    }

    /**
     * 获得用户资料
     *
     * @param int $uid 用户id
     *
     * @return mixed
     */
    protected function getUserInfo($uid)
    {
        static $user_info = [];

        $user = Db::name($this->config['auth_user']);
        // 获取用户表主键
        $_pk = is_string($user->getPk()) ? $user->getPk() : 'uid';
        if ( ! isset($user_info[$uid])) {
            $user_info[$uid] = $user->where($_pk, $uid)->find();
        }

        return $user_info[$uid];
    }

    /**
     * 取出当前管理员所拥有权限的管理员
     *
     * @param boolean $withself 是否包含自身
     *
     * @return array
     */
    public static function getChildrenAdminIds($withself = false)
    {
        $uid = cmf_get_admin_id();

        $childrenAdminIds = [];
        if ( ! self::isSuperAdmin($uid)) {
            $groupIds      = self::getChildrenGroupIds(true);
            $authGroupList = AuthGroupAccess::field('uid,group_id')->where('group_id', 'in', $groupIds)->select();
            foreach ($authGroupList as $k => $v) {
                $childrenAdminIds[] = $v['uid'];
            }
        } else {
            $childrenAdminIds = Admin::column('id');
        }
        if ($withself) {
            if ( ! in_array($uid, $childrenAdminIds)) {
                $childrenAdminIds[] = $uid;
            }
        } else {
            $childrenAdminIds = array_diff($childrenAdminIds, [$uid]);
        }
        $childrenAdminIds = array_values(array_unique($childrenAdminIds));

        return $childrenAdminIds;

    }

    /**
     * 判断是否超级管理
     * @return bool
     */
    public static function isSuperAdmin($uid)
    {
        return in_array('*', self::getRuleIds($uid)) ? true : false;
    }

    /**
     *
     * 取出当前管理员所拥有权限的分组
     *
     * @param boolean $withself 是否包含当前所在的分组
     *
     * @param         $withself
     *
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public static function getChildrenGroupIds($withself = false, $uid = 0)
    {
        if (empty($uid)) {
            $uid = cmf_get_admin_id();
        }
        $groups         = self::getGroups($uid);
        $groupIds       = array_column($groups->toArray(), 'id');
        $originGroupIds = $groupIds;
        foreach ($groups as $k => $v) {
            if (in_array($v['pid'], $originGroupIds)) {
                $groupIds = array_diff($groupIds, [$v['id']]);
                unset($groups[$k]);
            }
        }
        $groupList = AuthGroup::where(['status' => 1])->select();
        $objList   = [];
        foreach ($groups as $k => $v) {
            if ($v['rules'] === '*') {
                $objList = $groupList;
                break;
            }
            // 取出包含自己的所有子节点
            $childrenList = Tree2::instance()->init($groupList)->getChildren($v['id'], true);
            $obj          = Tree2::instance()->init($childrenList)->getTreeArray($v['pid']);
            $objList      = array_merge($objList, Tree2::instance()->getTreeList($obj));
        }
        $childrenGroupIds = [];
        foreach ($objList as $k => $v) {
            $childrenGroupIds[] = $v['id'];
        }

        if ( ! $withself) {
            $childrenGroupIds = array_diff($childrenGroupIds, $groupIds);
        }

        return $childrenGroupIds;
    }
}
